<template>
  <div class="app-container">
    <el-row class="row">
      <div class="action">
        <el-button class="filter-item" icon="el-icon-plus" type="primary" @click="handleCreate">新增用户</el-button>
      </div>
      <el-table :data="list"  element-loading-text="Loading" border fit highlight-current-row>
        <el-table-column align="center" label='时间' >
          <template slot-scope="scope">
            {{scope.row.createtime}}
          </template>
        </el-table-column>
        <el-table-column label="用户名">
          <template slot-scope="scope">
            {{scope.row.username}}
          </template>
        </el-table-column>
        <el-table-column label="公司">
          <template slot-scope="scope">
            {{scope.row.company}}
          </template>
        </el-table-column>
        <el-table-column label="手机号码">
          <template slot-scope="scope">
            {{scope.row.mobile}}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            {{scope.row.delflagstr}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="230" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleUpdate(scope.row)" >编辑</el-button>
            <router-link class="link-type" :to="'/user/children/'+scope.row.id">
              <el-button type="primary" size="mini" icon="el-icon-edit">子账户管理</el-button>
            </router-link>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-row>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form  autoComplete="on" :model="userForm" :rules="userRules" ref="userForm"  label-position="left">
        <el-input type="hidden" v-model="userForm.id"></el-input>
        <el-form-item label="用户id" prop="accountid">
          <el-input v-model="userForm.accountid" v-if="textMap[dialogStatus]=='编辑用户信息'"  :disabled="true" ></el-input>
          <el-input v-model="userForm.accountid" placeholder="请输入用户id" v-else></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="公司" prop="company">
          <el-input v-model="userForm.company" placeholder="请输入公司"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="userForm.mobile" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input name="password" :type="pwdType" v-model="userForm.password" placeholder="请输入用户密码"></el-input>
          <span class="show-password" @click="showPwd"><svg-icon icon-class="eye" /></span>
        </el-form-item>
        <el-form-item label="状态" prop="delflag">
          <el-select v-model="userForm.delflag" style="margin-right: 80%" placeholder="请选择">
            <el-option v-for="item in  statusOptions" :key="item.key" :label="item.text" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">创建</el-button>
        <el-button v-else type="primary" @click="updateData">修改</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  import { validateMobile } from '@/utils/validate'
  import { fetchList, saveUser } from '@/api/user'
  import { parseTime } from '@/utils/index'

  export default {
    name: 'user',
    data() {
      const validatePhone = (rule, value, callback) => {
        if (!validateMobile(value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      }
      return {
        list: [],
        total: null,
        listLoading: true,
        listQuery: {
          pageNum: 1,
          pageSize: 20,
          pid: ''
        },
        statusOptions: [
          { key: 0, text: '启用' },
          { key: 1, text: '禁用' }
        ],
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑用户信息',
          create: '新建用户'
        },
        userRules: {
          accountid: [{ required: true, message: '请输入用户id', trigger: 'blur' },
            { min: 1, max: 20, message: '长度在1到16字符', trigger: 'blur' }],
          username: [{ required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 1, max: 20, message: '长度在1到16字符', trigger: 'blur' }],
          company: [{ required: true, message: '请输入公司名称', trigger: 'blur' },
            { min: 1, max: 20, message: '长度在1到16中文字', trigger: 'blur' }],
          mobile: [{ required: true, message: '请输入正确的手机号码', trigger: 'blur', validator: validatePhone }],
          password: [{ required: true, message: '请输入用户密码', trigger: 'blur' }]
        },
        userForm: {
          id: '',
          pid: '',
          accountid: '',
          username: '',
          password: '',
          company: '',
          mobile: '',
          delflag: '',
          delflagstr: ''
        },
        pwdType: 'password'
      }
    },
    created() {
      this.userForm.pid = sessionStorage.getItem('id')
      this.listQuery.pid = sessionStorage.getItem('id')
      this.getList()
    },
    methods: {
      showPwd() {
        if (this.pwdType === 'password') {
          this.pwdType = ''
        } else {
          this.pwdType = 'password'
        }
      },
      resetForm() {
        this.userForm = {
          id: '',
          pid: sessionStorage.getItem('id'),
          accountid: '',
          username: '',
          company: '',
          mobile: '',
          delflag: undefined
        }
      },
      getList() {
        this.listLoading = true
        fetchList(this.listQuery).then(response => {
          if (response.code === 1) {
            const list = response.data.list
            this.total = response.data.total
            this.list = []
            for (const v of list) {
              const item = {}
              item.id = v.id
              item.accountid = v.accountid
              item.createtime = v.createtime
              item.username = v.username
              item.company = v.company
              item.mobile = v.mobile
              item.delflag = v.delflag
              if (v.delflag === 0) {
                item.delflagstr = '启用'
              } else {
                item.delflagstr = '禁用'
              }
              this.list.push(item)
            }
            // Just to simulate the time of the request
            setTimeout(() => {
              this.listLoading = false
            }, 1.5 * 1000)
          }
        })
      },
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val
        this.getList()
      },
      handleCreate() {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['userForm'].clearValidate()
        })
      },
      childManage(row) {
        this.userForm = Object.assign({}, row) // copy obj
        this.$router.push({
          name: 'children',
          params: {
            pid: this.userForm.id
          }
        })
        this.$router.push({ path: '/user/children' })
      },
      handleUpdate(row) {
        this.userForm = Object.assign({}, row) // copy obj
        this.userForm.password = ''
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['userForm'].clearValidate()
        })
      },
      createData() {
        this.$refs.userForm.validate(valid => {
          if (valid) {
            saveUser(this.userForm).then(() => {
              const data = this.userForm
              const time = parseTime(new Date())
              data.createtime = time
              this.list.unshift(this.userForm)
              this.dialogFormVisible = false
              this.$message({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            console.log('新建用户失败！')
            return false
          }
        })
      },
      updateData() {
        const fieldList = ['accountid', 'username', 'mobile', 'company']
        var form = this.$refs.userForm
        var flag = 1
        Promise.all(fieldList.map(item => {
          return form.validateField(item, (valid) => {
            console.log(valid)
            if (valid) {
              flag = 0
            }
          })
        }))
        if (flag === 1) {
          saveUser(this.userForm).then(() => {
            for (const v of this.list) {
              if (v.id === this.userForm.id) {
                const index = this.list.indexOf(v)
                if (this.userForm.delflag === 0) {
                  this.userForm.delflagstr = '启用'
                } else {
                  this.userForm.delflagstr = '禁用'
                }
                this.list.splice(index, 1, this.userForm)
                break
              }
            }
            this.dialogFormVisible = false
            this.$message({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      }
    }
  }
</script>
